package com.geek.novel.adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.drawable.ColorDrawable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.geek.novel.R
import com.geek.novel.entity.BookRead
import com.geek.novel.ui.BookImageView
import com.geek.novel.utils.DateUtil

/**我的书架列表的适配器*/
class MyBookListAdapter(context: Activity, list: ArrayList<BookRead>)
    : BaseRecyclerViewAdapter<MyBookListAdapter.ViewHolder, BookRead>(context, list) {

    //定义内部类ViewHolder，并继承RecyclerView.ViewHolder传入View参数通常是Recycler View子项的最外层布局
    class ViewHolder(view: View, adapter: BaseRecyclerViewAdapter<BaseRecyclerViewHolder, Any>): BaseRecyclerViewHolder(view, adapter) {
        val tvBookName: TextView
        val tvBookLastSection: TextView
        val tvBookUpdateTime: TextView
        val bookImageView: BookImageView
        init {
            tvBookName = view.findViewById(R.id.tv_book_name)
            tvBookLastSection = view.findViewById(R.id.tv_book_last_section)
            tvBookUpdateTime = view.findViewById(R.id.tv_book_update_time)
            bookImageView = view.findViewById(R.id.iv_my_book_image)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.listview_book, parent, false)
        return ViewHolder(view, this as BaseRecyclerViewAdapter<BaseRecyclerViewHolder, Any>)
    }


    /**绑定容器显示控件内容*/
    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        //设置书籍名称、书籍最新章节、书籍图片等等数据
        val book = list[position]
        holder.tvBookName.text = book.bookName

        //书籍最新章节
        var lastSectionName = book.lastIndexName
        if(TextUtils.isEmpty(lastSectionName)){
            lastSectionName = "无"
        }
        holder.tvBookLastSection.text = "最新：$lastSectionName"

        //书籍更新时间
        holder.tvBookUpdateTime.text = DateUtil.formatDate(book.lastIndexUpdateTime)

        //置顶了的话，背景显示灰色
        if(book.top){
            holder.itemView.background = ColorDrawable(context.getColor(R.color.bg_my_book_list_is_top))
        }else{
            holder.itemView.background = context.getDrawable(R.drawable.bg_list_item_book)
        }

        //图片
        val imgId = book.imgId
        val bookName = book.bookName
        holder.bookImageView.setBookName(bookName)
        holder.bookImageView.loadBookImage(imgId)

        //调用父类的方法，主要用于绑定事件
        super.onBindViewHolder(holder, position)

    }

}